﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LogisticDatabase.Models;
using LogisticDatabase.Data;


namespace LogisticDatabase
{
    public class FactoryDataAccess:IDataAccess<Factory>
    {
        public List<Factory> listAll()
        {
            List<Factory> factories = new List<Factory>();
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                factories = ctx.tblFactory.Select(t => new Factory
                {
                    Id = t.FactoryID,
                    Name = t.FactoryName,
                    City =
                        new City { Id = t.tblCity.CityID, Name = t.tblCity.CityName, Country = t.tblCity.CityCountry },
                    ProductList = t.tblProduct.Select( p=> new Product { Id = p.ProductID, Name = p.ProductName, Price = p.ProductPrice}).ToList()
                }).ToList();
            }
            return factories;
        }
        public void edit(Factory factory)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblFactory.FirstOrDefault(t => t.FactoryID == factory.Id);
                if (c != null)
                {
                    c.FactoryName = factory.Name;
                    c.CityNameFK = factory.City.Id;

                    ctx.SaveChanges();
                }



            }
        }
        public void add(Factory factory)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                tblFactory tf = new tblFactory();

                tf.FactoryName = factory.Name;
                tf.CityNameFK = factory.City.Id;

                ctx.tblFactory.Add(tf);

                ctx.SaveChanges();
            }
        }
        public void delete(Factory factory)
        {
            using (LogisticDatabaseEntity ctx = new LogisticDatabaseEntity())
            {
                var c = ctx.tblFactory.FirstOrDefault(t => t.FactoryID == factory.Id);
                if (c != null)
                {
                    ctx.tblFactory.Remove(c);
                    ctx.SaveChanges();
                }
            }

        }

    }
}
